package com.example.flowerback.service.impl;

import com.example.flowerback.mapper.LoginInOutMapper;
import com.example.flowerback.entity.User;
import com.example.flowerback.mode.Login;
import com.example.flowerback.mode.RegisterUser;
import com.example.flowerback.mode.UserType;
import com.example.flowerback.service.loginInOutService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class LoginInOutServiceImpl implements loginInOutService {
    @Autowired
    LoginInOutMapper loginInOutMapper;

    @Override
    public String registerUser(RegisterUser registerUser) {
        log.info("用户注册{}", registerUser);

        // 检查 role 是否为空
        if (registerUser.getRole() == null) return "role cannot be null";

        // 商家角色需要提供营业执照
        if ("seller".equals(registerUser.getRole()) && registerUser.getBusinessLicense() == null) {
            return "商家角色必须提供营业执照";
        }
        String status = "active";
        // 设置默认状态为 inactive（未激活）
        if ("seller".equals(registerUser.getRole()) || "admin".equals(registerUser.getRole())){
            status = "inactive";
        }

        // 这里根据 registerUser 填充 User 实体类
        User user = new User();
        user.setUsername(registerUser.getUsername());
        user.setPassword(registerUser.getPassword());
        user.setEmail(registerUser.getEmail());
        user.setPhone(registerUser.getPhone());
        user.setRole(registerUser.getRole());
        user.setStatus(status);
        user.setBusinessLicense(registerUser.getBusinessLicense());

        // 插入数据到数据库
        Integer userNum = loginInOutMapper.registerUser(registerUser);

        log.info("成功插入的数据条数{}", userNum);
        if (userNum > 0) return "注册成功，请等待管理员激活账户";
        return "注册失败";
    }

    @Override
    public String login(Login login) {
        String username = login.getUsername();
        String userPassword = login.getPassword();
        String userRole = login.getRole();
        // 获取用户信息
        Login info = loginInOutMapper.getUserInfo(username, userPassword, UserType.valueOf(userRole));

        if (info == null) return "用户不存在";

        // 检查密码
        if (!info.getPassword().equals(userPassword)) {
            return "密码错误";
        }

        // 检查用户状态
        if ("inactive".equals(info.getStatus())) {
            return "账户尚未激活，请等待管理员激活";
        }

        // 登录成功后，返回不同的角色信息
        switch (info.getRole()) {
            case "super_admin":
                return "欢迎进入超级管理员系统！";
            case "admin":
                return "欢迎进入管理员系统！";
            case "seller":
                return "欢迎进入商家系统！";
            case "buyer":
                return "欢迎进入买家系统！";
            default:
                return "系统错误！";
        }
    }
}
